package com.zyp.jobseeker.config;

import com.zyp.jobseeker.utils.ResultUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 全局响应拦截器：根据业务 code 设置 HTTP 状态码
 */
@RestControllerAdvice
public class GlobalResponseAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 只处理返回类型为 ResultUtil 的接口
        return returnType.getParameterType().equals(ResultUtil.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof ResultUtil) {
            ResultUtil<?> result = (ResultUtil<?>) body;
            // 直接使用 ResultUtil 中的 getHttpStatus() 方法设置 HTTP 状态码
            response.setStatusCode(result.getHttpStatus());
        }
        return body;
    }
}